import { useUserStore } from '@/stores/user'
import axios, { type Method } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '@/router'

// 封装登录接口
const service = axios.create({
  baseURL:'https://api-hmzs.itheima.net/tj',
  timeout: 20 * 1000
})


// 登录返回接口
export interface ServiceResponse<T>{
  code:number,
  msg:string,
  data:T
}


// 封装请求工具函数
  export const request  =<T>( url :string, method :Method ='GET',submitData?:object )=>{
  return service.request<T,ServiceResponse<T>>({
    url:url,
    method:method,
    [ method.toUpperCase() ==='GET' ?'params': 'data'] : submitData
  })  
}


service.interceptors.request.use(
  config => {
    const { token } = useUserStore()
    if(token){
      config.headers.Authorization =`Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  response => {
    return response.data
    
  },
  error => {
    if(error.response){
      // 根据响应的错误信息判断用户是否有网络
      // 如果有返回后端错误信息
      ElMessage.error({
        message:error.response.data.msg
      })
      // 根据状态码，判断登录信息是否无效
      if(error.response.status === 401 ){
        // 跳转到登录页
        router.push('/login')
        const store = useUserStore()
        store.removeToken()
      }
      
    }else{
      // 提示用户网络错误
      ElMessage.error('网络错误，请稍后再试')
    }
    return Promise.reject(error)
  },
)

export default service
